package com.lims;

import com.lims.utils.ValidateUtils;

import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author limaosheng
 * @create 2022-11-18 14:58
 * @desc
 */
public class 从数据库查询数据后判断信息是否正确 {

    public final static String DB_URL = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&useSSL=false&serverTimezone=GMT%2B8";
    public final static String DB_USER = "root";
    public final static String DB_PWD = "123456";

    public static void main(String[] args) {
        //查询人员信息
        String sql = "select * from test_user";
        Connection conn = null;
        List<Map<String, Object>> list = new ArrayList<>();
        try {
            conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PWD);
            PreparedStatement ps1 = conn.prepareStatement(sql);
            ResultSet rs1 = ps1.executeQuery();
            ResultSetMetaData md = rs1.getMetaData();
            int columnCount = md.getColumnCount();
            while (rs1.next()) {
                Map<String, Object> rowData = new HashMap<String, Object>();
                for (int i = 1; i <= columnCount; i++) {
                    rowData.put(md.getColumnName(i), rs1.getObject(i));
                }
                list.add(rowData);
            }

            for (Map<String, Object> map : list) {
                try {
                    //例子
                    Object objName = map.get("name");
                    if (objName != null) {
                        String name = objName.toString();
                        if (!ValidateUtils.isName(name)) {
                            String updateSql = "update test_user set name = '测试名' where id = " + map.get("id");
                            PreparedStatement ps2 = conn.prepareStatement(updateSql);
                            int i = ps2.executeUpdate();
                        }
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception throwables) {
            throwables.printStackTrace();
        } finally {
            closeConn(conn);
        }
    }

    public static void closeConn(Connection conn) {
        try {
            if (conn != null) {
                conn.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
